// 导入数据库操作模块
const db = require('../db/index')

// 获取用户信息处理函数
exports.getUserInfo = (req, res) => {
    // 定义查询sql语句
    const sql = 'select username,nickname,email,avatar from users where id=?'
    // console.log(req.auth)
    db.query(sql, req.auth.id, (err, results) => {
        if (err) return res.send({
            status: 1,
            message: err
        })
        if (!results) return res.send({
            status: 1,
            message: '获取用户信息失败!'
        })
        delete req.auth.password
        return res.send({
            status: 0,
            message: '获取用户信息成功',
            data: req.auth
        })
    })
}

// 更新用户密码处理函数
exports.updatePassword = (req, res) => {
    console.log(req.body)
    const {oldpassword, newpassword} = req.body
    // 定义sql查询语句
    const sql = 'select password from users where id=?'
    db.query(sql, req.auth.id, (err, results) => {
        if (err) return res.send({
            status: 1,
            message: err
        })
        if (!results) return res.send({
            status: 1,
            message: '用户不存在!'
        })
        if (newpassword === results[0].password) return res.send({
            status: 1,
            message: '新密码与原密码一致!'
        })
        if (req.auth.id === 1, results[0].password === '123456') return res.send({
            status: 1,
            message: '管理员密码不可修改!'
        })
        if (oldpassword !== results[0].password) return res.send({
            status: 1,
            message: '原密码错误!'
        })
        // 定义修改sql语句
        const sql1 = 'update users set password=? where id=?'
        db.query(sql1, [newpassword, req.auth.id], (err, results) => {
            if (err) return res.send({
                status: 1,
                message: err
            })
            if (results.affectedRows !== 1) return res.send({
                status: 1,
                message: '更新密码失败!'
            })
            return res.send({
                status: 0,
                message: '更新密码成功!',
                data: null
            })
        })
    })
}
// 添加用户账号路由处理函数
exports.addAccount = (req, res) => {
    res.send('ok')
}

// 退出登录处理函数
exports.logout = (req, res) => {
    req.auth = {}
    res.send({
        status: 0,
        message: '退出登录成功!',
        data: null
    })
}